package cn.liuxiany.alibaba.flowable.service.impl;

import cn.liuxiany.alibaba.flowable.service.BpmProcessDefinitionService;
import lombok.extern.slf4j.Slf4j;
import org.flowable.common.engine.impl.db.SuspensionState;
import org.flowable.engine.RepositoryService;
import org.flowable.engine.repository.ProcessDefinition;
import org.flowable.engine.repository.ProcessDefinitionQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author liuxiany
 * @date 2023/10/26
 */
@Slf4j
@Service
public class BpmProcessDefinitionServiceImpl implements BpmProcessDefinitionService {

    @Autowired
    private RepositoryService repositoryService;

    @Override
    public Object getProcessDefinitionList(Integer suspensionState) {
        // 拼接查询条件
        ProcessDefinitionQuery definitionQuery = repositoryService.createProcessDefinitionQuery();
        if (Objects.equals(SuspensionState.SUSPENDED.getStateCode(), suspensionState)) {
            definitionQuery.suspended();
        } else if (Objects.equals(SuspensionState.ACTIVE.getStateCode(), suspensionState)) {
            definitionQuery.active();
        }
        // 执行查询
        List<ProcessDefinition> processDefinitions = definitionQuery.list();
        if (CollectionUtils.isEmpty(processDefinitions)) {
            return Collections.emptyList();
        }

        List<String> keys = processDefinitions.stream().map(ProcessDefinition::getKey).filter(Objects::nonNull).collect(Collectors.toList());


        return keys;
    }
}
